package atom.core2.j2ee.tag.util;

import java.util.Iterator;
import java.util.List;

import atom.core0.j2ee.page.PageResult;


/**
 * google html navigator.
 * 
 * <pre>
 * [上一页]1 2 3 4 5 6 7 8 9 [下一页]
 * </pre>
 * 
 * @author haichen.ma
 * 
 */
public class GoogleHtmlNavigator implements HtmlNavigator {
	private static final int BATCH_SIZE = 10;

	public String getHtmlNavigation(String contextPath, PageResult p, int formIndex, boolean tidy) {
		StringBuffer html = new StringBuffer();
		html.append("<div class=\"pageNavigation\">");
		html.append("    <input type='hidden' id='pageSize_" + formIndex + "' value='" + p.getPageSize() + "' />");
		if (tidy) {
			html.append("<a href=\"javascript: Paginater.toPage(" + formIndex + "," + p.getCurrentPage()
					+ ")\" id=\"_refresh\" style=\"display:none\">[刷新]</a>");
			html.append(getBatchPages(p, formIndex));
		} else {
			html.append("<a href=\"javascript: Paginater.toPage(" + formIndex + "," + p.getCurrentPage()
					+ ")\" id=\"_refresh\" style=\"display:none\">[刷新]</a>");

			if (p.getCurrentPage() != p.getFirstPage()) {
				html.append("<a href=\"javascript:Paginater.toPage(" + formIndex + "," + p.getPriorPage() + ")\">[上一页]</a>");
			}

			//没有数据或者只有一页数据时，不显示分页按钮
			if (p.getTotalRowCount() != 0 && p.getTotalPageCount() != 1) {
				html.append(getBatchPages(p, formIndex));
			}

			if (p.getCurrentPage() != p.getLastPage() && p.getTotalRowCount() != 0) {
				html.append("<a href=\"javascript:Paginater.toPage(" + formIndex + "," + p.getNextPage() + ")\">[下一页]</a>");
			}
		}

		html.append("</div>");

		return html.toString();
	}

	private StringBuffer getBatchPages(PageResult p, int formIndex) {
		List batchPages = p.getBatchPages(BATCH_SIZE);
		StringBuffer pages = new StringBuffer();

		for (Iterator i = batchPages.iterator(); i.hasNext();) {
			String page = (String) i.next();

			if (p.getCurrentPage() == Integer.parseInt(page)) {
				pages.append(" <font style='font-weight:bold;color: #E74705;'>" + page + "</font> ");
			} else {
				pages.append(" <a href=\"javascript:Paginater.toPage(" + formIndex + "," + page + ")\">" + page + "</a> ");
			}
		}

		return pages;
	}

}
